Laravel6在確保資料庫操作沒有問題後,再正式提交(commit)這次操作。若操作到一半出錯時,可將前半部的操作取消(rollback)。
如此可以保證同一批次操作的完整性。
* 程式碼如下:
use Illuminate\Support\Facades\DB;
DB::beginTransaction();
                try {
                   
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return response()->json(['result'=>$th],403);
                }
                DB::commit();
use Illuminate\Support\Facades\DB;
DB::beginTransaction();
                try {
                    $reward->update([
                        'hunters'=>$hunter_reward,
                        'bonus'=>$hunter_reward->fee,
                        'chosen'=>1]);
    
                    $user=User::where('id',$reward->user_id)->first();
                    $user->update([
                            'cost'=>$user->cost + $hunter_reward->fee - $reward->budget,
                            ]);
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return response()->json(['result'=>$th],403);
                }
                DB::commit();